package org.jeecg.modules.third.kaiyunshukedaikai;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.third.digitalseal.utils.GeneratePDF;
import org.jeecg.modules.third.kaiyunshukedaikai.entity.*;
import org.jeecg.modules.third.openapi.WaybillRouteService;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleType;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.entity.PointDataListVO;
import org.jeecg.modules.wlhy.shipping.entity.WaybillRouteVO;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@Service
public class KaiyunService {

    @Value(value = "${kaiyun.appid:}")
    private String appid;

    @Value(value = "${kaiyun.appsecret:}")
    private String appsecret;

    @Value(value = "${kaiyun.url:}")
    private String url;

    @Value(value = "${kaiyun.yuming:}")
    private String yuming;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Value(value = "${jeecg.path.bank}")
    private String bankpath;


    @Autowired
    private IHyCustomerService hyCustomerService;

    @Autowired
    private WaybillRouteService waybillRouteService;

    @Autowired
    private IHyShippingNoteService shippingNoteService;

    @Autowired
    private GeneratePDF generatePDF;

    @Autowired
    private IHyVehicleService vehicleService;

    /**
     * 添加驾驶员信息接口测试
     *
     * @throws UnsupportedEncodingException
     */
    public Result<?> addDriver(HttpServletRequest req, HyDriver driver) {

//        String appid = "hnxzeeuvIm73";
//        String appsecret = "0ec49d56b0de3bd489bb97a915127fdd1df642ef";
        if (driver != null) {
            //业务数据
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            KaiyunDriver kaiyunDriver = new KaiyunDriver();
            kaiyunDriver.setId_card_no(driver.getIdcard());
            kaiyunDriver.setReal_name(driver.getDriverName());
            kaiyunDriver.setAddr("1");
            kaiyunDriver.setQual_cert_id(driver.getQualificationCertificate());
            kaiyunDriver.setMobile(driver.getTelephone());
            kaiyunDriver.setQuasi_driving_type(driver.getVehicleClass());
            kaiyunDriver.setCarrier_id_card_no(driver.getIdcard());
            kaiyunDriver.setCarrier_mobile(driver.getTelephone());
            String domainName = yuming+"/static/";
            kaiyunDriver.setId_pic1_pic_url(domainName + driver.getIdcardImg());
            kaiyunDriver.setId_pic2_pic_url(domainName + driver.getIdcardImgBack());
            kaiyunDriver.setDriver_lic_pic_url(domainName + driver.getDriverImg());
            kaiyunDriver.setDriver_lic_side_pic_url(domainName + driver.getDriverImg2());
            kaiyunDriver.setQual_cert_pic_url(domainName + driver.getQualificationImg());
            kaiyunDriver.setAddr(driver.getAddress());
            kaiyunDriver.setDriver_lic_sign_org(driver.getIssuingOrganizations());
            kaiyunDriver.setDriver_lic_no(driver.getDrivingLicense());
            kaiyunDriver.setDriver_lic_valid(simpleDateFormat.format(driver.getValidPeriodFrom()) + "至" + simpleDateFormat.format(driver.getValidPeriodTo()));
            kaiyunDriver.setValidity(simpleDateFormat.format(driver.getIdcardValidFrom()) + "至" + simpleDateFormat.format(driver.getIdcardExpiredDate()));

            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(kaiyunDriver), Map.class);
            Long _aop_strtotime = System.currentTimeMillis() / 1000;
            //获取签名
            TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
            log.info("添加驾驶人接口参数：" + map2);
            HttpEntity reqEntity = null;
            try {
                reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                String result = TestHttpClientUtil.httpPost(url+"/car/ApiDriver/add?appid=" + appid +
                        "&_aop_strtotime=" + _aop_strtotime, reqEntity);

                ObjectMapper objectMapper = new ObjectMapper();
                ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
                log.info(resultDto);
                if(resultDto!=null){
                    if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                        return Result.OK(result);
                    }else{
                        return Result.error(resultDto.getMsg());
                    }
                }else{
                    return Result.error("数据转换失败"+result);
                }

            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.toString());
            }
        } else {
            return Result.error("司机数据为空");
        }


    }

    /**
     * 编辑驾驶员信息接口
     *
     * @throws UnsupportedEncodingException
     */
    public Result<?> editDriver(HttpServletRequest req, HyDriver driver) {

//        String appid = "hnxzeeuvIm73";
//        String appsecret = "0ec49d56b0de3bd489bb97a915127fdd1df642ef";
        if (driver != null) {
            //业务数据
           /* private String real_name;                        //姓名
            private String gender;                           //性别     1：男   2：女(可选)
            private String qual_cert_id;                     //从业资格证信息号(4.5t以上的必传)
            private String mobile;                           //驾驶员手机号
            private String quasi_driving_type;               //准驾车型
            private String carrier_id_card_no;               //承运人身份证号码
            private String carrier_mobile;                   //承运人手机号
            private String id_pic1_pic_url;                  //身份证头像面
            private String id_pic2_pic_url;                  //身份证国徽面
            private String driver_lic_pic_url;               //驾驶证图片
            private String driver_lic_side_pic_url;          //驾驶证副页图片(可选)
            private String qual_cert_pic_url;                //从业资格证图片(4.5t以上的必传)
            private String addr;                             //身份证地址
            private String driver_lic_sign_org;              //驾驶证发证机关
            private String driver_lic_no;                    //驾驶证编号
            private String driver_lic_valid;                 //驾驶证有效期("yyyy-MM-dd至yyyy-MM-dd"  或者 "yyyy-MM-dd至长期")
            private String validity;                         //身份证有效期(可选，"yyyy-MM-dd至yyyy-MM-dd"  或者 "yyyy-MM-dd至长期")*/
            KaiyunDriver kaiyunDriver = new KaiyunDriver();
            kaiyunDriver.setId_card_no(driver.getIdcard());
            kaiyunDriver.setReal_name(driver.getDriverName());
            kaiyunDriver.setAddr("1");
            kaiyunDriver.setQual_cert_id(driver.getQualificationCertificate());
            kaiyunDriver.setMobile(driver.getTelephone());
            kaiyunDriver.setQuasi_driving_type(driver.getVehicleClass());
            kaiyunDriver.setCarrier_id_card_no(driver.getIdcard());
            kaiyunDriver.setCarrier_mobile(driver.getTelephone());
            String domainName =yuming+"/static/";
            kaiyunDriver.setId_pic1_pic_url(domainName + driver.getIdcardImg());
            kaiyunDriver.setId_pic2_pic_url(domainName + driver.getIdcardImgBack());
            kaiyunDriver.setDriver_lic_pic_url(domainName + driver.getDriverImg());
            kaiyunDriver.setDriver_lic_side_pic_url(domainName + driver.getDriverImg2());
            kaiyunDriver.setQual_cert_pic_url(domainName + driver.getQualificationImg());
            kaiyunDriver.setAddr(driver.getAddress());
            kaiyunDriver.setDriver_lic_sign_org(driver.getIssuingOrganizations());
            kaiyunDriver.setDriver_lic_no(driver.getDrivingLicense());
            kaiyunDriver.setDriver_lic_valid(driver.getValidPeriodFrom() + "至" + driver.getValidPeriodTo());
            kaiyunDriver.setValidity(driver.getIdcardValidFrom() + "至" + driver.getIdcardExpiredDate());

            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(kaiyunDriver), Map.class);
            Long _aop_strtotime = System.currentTimeMillis() / 1000;
            //获取签名
            TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
            log.info("编辑驾驶员信息接口：" + map2);
            HttpEntity reqEntity = null;
            try {
                reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                String result = TestHttpClientUtil.httpPost(url+"/car/ApiDriver/edit?appid=" + appid +
                        "&_aop_strtotime=" + _aop_strtotime, reqEntity);
                ObjectMapper objectMapper = new ObjectMapper();
                ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
                log.info(resultDto);
                if(resultDto!=null){
                    if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                        return Result.OK(result);
                    }else{
                        return Result.error(resultDto.getMsg());
                    }
                }else{
                    return Result.error("数据转换失败"+result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.toString());
            }
        } else {
            return Result.error("司机数据为空");
        }
    }

    /**
     * 驾驶员认证状态查询
     *
     * @throws UnsupportedEncodingException
     */
    public Result<?> getApiDriverStatus(String mobile) {
        // 实体类转换为Map
        Map<String, String> map2 = new HashMap<>();
        map2.put("mobile", mobile);
        Long _aop_strtotime = System.currentTimeMillis() / 1000;
        //获取签名
        TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
        log.info("驾驶员认证状态查询：" + map2);
        HttpEntity reqEntity = null;
        try {
            reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
            String result = TestHttpClientUtil.httpPost(url+"/car/ApiDriver/edit?appid=" + appid +
                    "&_aop_strtotime=" + _aop_strtotime, reqEntity);
            ObjectMapper objectMapper = new ObjectMapper();
            ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
            log.info(resultDto);
            if(resultDto!=null){
                if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                    return Result.OK(result);
                }else{
                    return Result.error(resultDto.getMsg());
                }
            }else{
                return Result.error("数据转换失败"+result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        }
    }

    /**
     * 车辆认证状态查询
     *
     * @param vehicleNumber 车牌号
     * @return
     */
    public Result<?> getApiVehicleStatus(String vehicleNumber) {
        // 实体类转换为Map
        Map<String, String> map2 = new HashMap<>();
        map2.put("vehicle_number", vehicleNumber);
        Long _aop_strtotime = System.currentTimeMillis() / 1000;
        //获取签名
        TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
        log.info("车辆认证状态查询：" + map2);
        HttpEntity reqEntity = null;
        try {
            reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
            String result = TestHttpClientUtil.httpPost(url+"/car/ApiVehicle/getStatus?appid=" + appid +
                    "&_aop_strtotime=" + _aop_strtotime, reqEntity);
            ObjectMapper objectMapper = new ObjectMapper();
            ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
            log.info(resultDto);
            if(resultDto!=null){
                if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                    return Result.OK(result);
                }else{
                    return Result.error(resultDto.getMsg());
                }
            }else{
                return Result.error("数据转换失败"+result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        }
    }


    /**
     * 添加车辆信息接口测试
     *
     * @throws UnsupportedEncodingException
     */
    public Result<?> addVehicle(HttpServletRequest req, HyVehicle vehicle, HyDriver driver) {

        if (vehicle != null) {
            //业务数据
            String domainName =  yuming+"/static/";
            KaiyunVehicle kaiyunVehicle = new KaiyunVehicle();
            kaiyunVehicle.setVehicle_number(vehicle.getVehicleNumber());
//            kaiyunVehicle.setLic_plate_code();
            List<HyVehicleType> hyVehicleTypeList = vehicleService.getHyVehicleByPid("1");
            HyVehicleType hyVehicleType = hyVehicleTypeList.stream().filter(s->vehicle.getVehicleType().contains(s.getText())).findAny().orElse(null);
            if (hyVehicleType == null) {
                return Result.error("车辆类型不存在,请修改后重新上报");
            }else{
                kaiyunVehicle.setVehicle_class_code(hyVehicleType.getValue());
            }

            kaiyunVehicle.setVehicle_plate_color("2");
//            kaiyunVehicle.setVehicle_plate_color();
            kaiyunVehicle.setVehicle_laden_weight("8000");
            kaiyunVehicle.setVehicle_tonnage(vehicle.getVehicleTonnage().multiply(new BigDecimal("1000")).toString());
            kaiyunVehicle.setVehicle_weight_type("0");
            kaiyunVehicle.setRoad_trans_cert_number(vehicle.getRoadTransportNumber());
            kaiyunVehicle.setId_card_no(driver.getIdcard());
            kaiyunVehicle.setCarrier_mobile(driver.getTelephone());
            kaiyunVehicle.setCarrier_name(vehicle.getRoadTransportName());
            kaiyunVehicle.setCarrier_type(vehicle.getIzAffiliation() == "1" ? "2" : "1");
            kaiyunVehicle.setDriving_license_pic_url(domainName + vehicle.getDrivingLicenseImg());
            kaiyunVehicle.setRoad_trans_cert_pic_url(domainName + vehicle.getRoadTransportImg());
            kaiyunVehicle.setFuel_type("02");
            kaiyunVehicle.setSign_org(vehicle.getIssuingOrganizations());
            kaiyunVehicle.setUse_character(vehicle.getUseCharacter());
            kaiyunVehicle.setIssue_date(String.valueOf(vehicle.getIssueDate().getTime()/1000));
            kaiyunVehicle.setDriving_lic_reg(String.valueOf(vehicle.getRegisterDate().getTime()/1000));
            kaiyunVehicle.setVeh_id_no(vehicle.getVin());

            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(kaiyunVehicle), Map.class);
            Long _aop_strtotime = System.currentTimeMillis() / 1000;
            //获取签名
            TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
            log.info("添加车辆信息接口测试：" + map2);
            HttpEntity reqEntity = null;
            try {
                reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                String result = TestHttpClientUtil.httpPost(url+"/car/ApiVehicle/add?appid=" + appid +
                        "&_aop_strtotime=" + _aop_strtotime, reqEntity);
                ObjectMapper objectMapper = new ObjectMapper();
                ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
                log.info(resultDto);
                if(resultDto!=null){
                    if(resultDto.getCode().equals("200") ){
                        return Result.OK(result);
                    }else{
                        return Result.error(resultDto.getMsg());
                    }
                }else{
                    return Result.error("数据转换失败"+result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.toString());
            }
        } else {
            return Result.error("司机数据为空");
        }
    }


    /**
     * 编辑车辆信息接口测试
     *
     * @throws UnsupportedEncodingException
     */
    public Result<?> editVehicle(HttpServletRequest req, HyVehicle vehicle, HyDriver driver) {

//        String appid = "hnxzeeuvIm73";
//        String appsecret = "0ec49d56b0de3bd489bb97a915127fdd1df642ef";
        if (vehicle != null) {
            //业务数据

            String domainName =  yuming+"/static/";
            KaiyunVehicle kaiyunVehicle = new KaiyunVehicle();
            kaiyunVehicle.setVehicle_number(vehicle.getVehicleNumber());
//            kaiyunVehicle.setLic_plate_code();
            List<HyVehicleType> hyVehicleTypeList = vehicleService.getHyVehicleByPid("1");
            HyVehicleType hyVehicleType = hyVehicleTypeList.stream().filter(s->vehicle.getVehicleType().contains(s.getText())).findAny().orElse(null);
            if (hyVehicleType == null) {
                return Result.error("车辆类型不存在,请修改后重新上报");
            }else{
                kaiyunVehicle.setVehicle_class_code(hyVehicleType.getValue());
            }

            kaiyunVehicle.setVehicle_plate_color("2");
//            kaiyunVehicle.setVehicle_plate_color();
            kaiyunVehicle.setVehicle_laden_weight("8000");
            kaiyunVehicle.setVehicle_tonnage(vehicle.getVehicleTonnage().multiply(new BigDecimal("1000")).toString());
            kaiyunVehicle.setVehicle_weight_type("0");
            kaiyunVehicle.setRoad_trans_cert_number(vehicle.getRoadTransportNumber());
            kaiyunVehicle.setId_card_no(driver.getIdcard());
            kaiyunVehicle.setCarrier_mobile(driver.getTelephone());
            kaiyunVehicle.setCarrier_name(vehicle.getRoadTransportName());
            kaiyunVehicle.setCarrier_type(vehicle.getIzAffiliation() == "1" ? "2" : "1");
            kaiyunVehicle.setDriving_license_pic_url(domainName + vehicle.getDrivingLicenseImg());
            kaiyunVehicle.setRoad_trans_cert_pic_url(domainName + vehicle.getRoadTransportImg());
            kaiyunVehicle.setFuel_type("02");
            kaiyunVehicle.setSign_org(vehicle.getIssuingOrganizations());
            kaiyunVehicle.setUse_character(vehicle.getUseCharacter());
            kaiyunVehicle.setIssue_date(String.valueOf(vehicle.getIssueDate().getTime()/1000));
            kaiyunVehicle.setDriving_lic_reg(String.valueOf(vehicle.getRegisterDate().getTime()/1000));
            kaiyunVehicle.setVeh_id_no(vehicle.getVin());

            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(kaiyunVehicle), Map.class);
            Long _aop_strtotime = System.currentTimeMillis() / 1000;
            //获取签名
            TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
            log.info("编辑车辆信息接口测试：" + map2);
            HttpEntity reqEntity = null;
            try {
                reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                String result = TestHttpClientUtil.httpPost(url+"/car/ApiVehicle/edit?appid=" + appid +
                        "&_aop_strtotime=" + _aop_strtotime, reqEntity);
                ObjectMapper objectMapper = new ObjectMapper();
                ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
                log.info(resultDto);
                if(resultDto!=null){
                    if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                        return Result.OK(result);
                    }else{
                        return Result.error(resultDto.getMsg());
                    }
                }else{
                    return Result.error("数据转换失败"+result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.toString());
            }
        } else {
            return Result.error("司机数据为空");
        }
    }


    /**
     * 新增承运人
     *
     * @param req
     * @param driver
     * @return
     */
    public Result<?> addApiCarrier(HttpServletRequest req, HyDriver driver) {

        if (driver != null) {
            //业务数据

            String domainName = yuming+"/static/";
            KaiyunCarrier kaiyunCarrier = new KaiyunCarrier();
            kaiyunCarrier.setId_card_no(driver.getIdcard());
            kaiyunCarrier.setReal_name(driver.getDriverName());
            kaiyunCarrier.setMobile(driver.getTelephone());
            kaiyunCarrier.setId_pic1_pic_url(domainName + driver.getIdcardImg());
            kaiyunCarrier.setId_pic2_pic_url(domainName + driver.getIdcardImgBack());
            kaiyunCarrier.setAddr(driver.getAddress());


            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(kaiyunCarrier), Map.class);
            Long _aop_strtotime = System.currentTimeMillis() / 1000;
            //获取签名
            TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
            log.info("新增承运人：" + map2);
            HttpEntity reqEntity = null;
            try {
                reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                String result = TestHttpClientUtil.httpPost(url+"/car/ApiCarrier/add?appid=" + appid +
                        "&_aop_strtotime=" + _aop_strtotime, reqEntity);
                ObjectMapper objectMapper = new ObjectMapper();
                ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
                log.info(resultDto);
                if(resultDto!=null){
                    if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                        return Result.OK(result);
                    }else{
                        return Result.error(resultDto.getMsg());
                    }
                }else{
                    return Result.error("数据转换失败"+result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.toString());
            }
        } else {
            return Result.error("司机数据为空");
        }
    }

    /**
     * 编辑承运人
     *
     * @param req
     * @param driver
     * @return
     */
    public Result<?> editApiCarrier(HttpServletRequest req, HyDriver driver) {

        if (driver != null) {
            //业务数据

            String domainName = yuming+"/static/";
            KaiyunCarrier kaiyunCarrier = new KaiyunCarrier();
            kaiyunCarrier.setId_card_no(driver.getIdcard());
            kaiyunCarrier.setReal_name(driver.getDriverName());
            kaiyunCarrier.setMobile(driver.getTelephone());
            kaiyunCarrier.setId_pic1_pic_url(domainName + driver.getIdcardImg());
            kaiyunCarrier.setId_pic2_pic_url(domainName + driver.getIdcardImgBack());
            kaiyunCarrier.setAddr(driver.getAddress());


            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(kaiyunCarrier), Map.class);
            Long _aop_strtotime = System.currentTimeMillis() / 1000;
            //获取签名
            TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
            log.info("编辑承运人：" + map2);
            HttpEntity reqEntity = null;
            try {
                reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                String result = TestHttpClientUtil.httpPost(url+"/car/ApiCarrier/edit?appid=" + appid +
                        "&_aop_strtotime=" + _aop_strtotime, reqEntity);
                ObjectMapper objectMapper = new ObjectMapper();
                ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
                log.info(resultDto);
                if(resultDto!=null){
                    if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                        return Result.OK(result);
                    }else{
                        return Result.error(resultDto.getMsg());
                    }
                }else{
                    return Result.error("数据转换失败"+result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.toString());
            }
        } else {
            return Result.error("司机数据为空");
        }
    }


    /**
     * 创建和编辑运单
     *
     * @param req
     * @param hyShippingNote
     * @return
     */
    public Result<?> addOrEditShippingNote(HttpServletRequest req, HyShippingNote hyShippingNote, List<HyShippingNoteBill> hyShippingNoteBills, HyDriver driver, HyVehicle vehicle) throws IOException {

        if (hyShippingNote != null) {
            //业务数据
            HyCustomer customer = hyCustomerService.getById(hyShippingNote.getCustomerId());
            if (customer == null) {
                return Result.error("货主数据为空");
            }

            //计算运费（存在多条）
            BigDecimal totalAmt = hyShippingNoteBills.stream().map(HyShippingNoteBill::getAmt).reduce(BigDecimal.ZERO, BigDecimal::add);

            String domainName = yuming+"/static/";
            String domainName2 = yuming+"/bank/";

            KaiyunShippingNote kaiyunShippingNote = new KaiyunShippingNote();
            kaiyunShippingNote.setGoods_no(hyShippingNote.getOrderId());  //合作方货源编号
            kaiyunShippingNote.setOrder_no(hyShippingNote.getShippingNoteNumber());  //合作方唯一业务单号(唯一)

            //用资金流水运费求和，不用costpay
            kaiyunShippingNote.setWaybill_amount(totalAmt.multiply(new BigDecimal("100")).toString());  //合同金额(含税、司机/船东的劳务费*1.03+油气费+过路费+其它费用、单位：分)
            kaiyunShippingNote.setInvoice_amount(totalAmt.multiply(new BigDecimal("100")).toString());  //开票金额(含税、司机的劳务费*1.03、单位：分、开票金额计算公式以商务合同约定为准)
            kaiyunShippingNote.setLabour_amount(totalAmt.multiply(new BigDecimal("100")).toString());  //运输劳务费用(不含税、单位：分) (司机实际收到的运费金额)
//            kaiyunShippingNote.setWaybill_amount(hyShippingNote.getCostPayShipping().multiply(new BigDecimal("100")).toString());  //合同金额(含税、司机/船东的劳务费*1.03+油气费+过路费+其它费用、单位：分)
//            kaiyunShippingNote.setInvoice_amount(hyShippingNote.getCostPayShipping().multiply(new BigDecimal("100")).toString());  //开票金额(含税、司机的劳务费*1.03、单位：分、开票金额计算公式以商务合同约定为准)
//            kaiyunShippingNote.setLabour_amount(hyShippingNote.getCostPayShipping().multiply(new BigDecimal("100")).toString());  //运输劳务费用(不含税、单位：分) (司机实际收到的运费金额)

            kaiyunShippingNote.setContract_time(String.valueOf(hyShippingNote.getCreateTime().getTime()/1000));  //合同签订日期(时间戳)
            kaiyunShippingNote.setCarrier_mobile(driver.getTelephone());  //承运人手机号(个体承运人为司机手机号)
            kaiyunShippingNote.setTransport_mobile(driver.getTelephone());  //司机手机号
            kaiyunShippingNote.setTrans_vehicle_name(vehicle.getVehicleNumber());  //运输工具名称（车牌号）
            kaiyunShippingNote.setGoods_type("1700");  //货物类型
            kaiyunShippingNote.setGoods_name(hyShippingNote.getDescriptionOfGoods());  //货物名称
            kaiyunShippingNote.setGoods_num(hyShippingNote.getGoodsWeightLoading().multiply(new BigDecimal("1000")).toString());  //货量
            kaiyunShippingNote.setGoods_unit("0");  //货量单位(见下方附加数据)
            kaiyunShippingNote.setLoad_time(String.valueOf(hyShippingNote.getStatusDtReceive().getTime()/1000));  //起运时间(时间戳)
            kaiyunShippingNote.setUnload_time(String.valueOf(hyShippingNote.getStatusDtUnloading().getTime()/1000));  //卸货时间(时间戳)
            kaiyunShippingNote.setFinish_time(String.valueOf(hyShippingNote.getPayDt().getTime()/1000));  //交易完成时间(时间戳)
            kaiyunShippingNote.setLoad_place_id(hyShippingNote.getSendAreaCode());  //装货地id
            kaiyunShippingNote.setUnload_place_id(hyShippingNote.getReceiveAreaCode());  //卸货地id
            kaiyunShippingNote.setLoad_place_detail(hyShippingNote.getSendAddress());  //装货地详细地址(不包含省市区)
            kaiyunShippingNote.setUnload_place_detail(hyShippingNote.getReceiveAddress());  //卸货地详细地址(不包含省市区
            kaiyunShippingNote.setShipper_contact_name(customer.getCustomerName());  //托运方联系人名称
            kaiyunShippingNote.setShipper_contact_mobile(driver.getTelephone());  //托运方手机号
            kaiyunShippingNote.setConsi_name(hyShippingNote.getReceiveAddress());  //收货方名称
            kaiyunShippingNote.setConsi_contact_name(hyShippingNote.getReceiveContactName());  //收货联系人姓名
//            kaiyunShippingNote.setConsi_contact_id      (hyShippingNote)        ;  //收货方联系人身份证 (可选)
            kaiyunShippingNote.setConsi_contact_mobile(hyShippingNote.getReceiveContactTel());  //收货人手机号


            Result result1 = generatePDF.pdfUtilServiceGet(hyShippingNote.getId());
            if(result1.isSuccess()){
                kaiyunShippingNote.setContract_pic(domainName + result1.getResult().toString());  //合同图片URL(支持图片和PDF,多个逗号拼接)
            }else{
                return Result.error("运输合同生成失败:"+result1.getMessage());
            }
            kaiyunShippingNote.setReply_pic(domainName+hyShippingNote.getImgUnloading());  //回单图片URL(支持图片和PDF,多个逗号拼接)

            Result driverSignAndRegister = generatePDF.kaiyundaikai(hyShippingNote.getOrderId(), driver, null);
            if(driverSignAndRegister.isSuccess()){
                kaiyunShippingNote.setDelegated_invoice_pic("01::"+domainName+driverSignAndRegister.getResult());  //合同图片URL(支持图片和PDF,多个逗号拼接)
            }else{
                return Result.error("税务代开合同生成失败:"+driverSignAndRegister.getMessage());
            }



//            kaiyunShippingNote.setOil_fee_amount        (hyShippingNote)        ;  //加油费累计(含税、单位：分)(可选)
//            kaiyunShippingNote.setGas_fee_amount        (hyShippingNote)        ;  //加气费累计(含税、单位：分)(可选)
//            kaiyunShippingNote.setRoad_fee_amount       (hyShippingNote)        ;  //过路费(含税、单位：分)(可选)
//            kaiyunShippingNote.setOther_fee_amount      (hyShippingNote)        ;  //其他费用(含税、单位：分)(可选)
//            kaiyunShippingNote.setApply_no_3th          (hyShippingNote)        ;  //客户销项发票单号(可选)
//            kaiyunShippingNote.setExt_carrier_mobile    (hyShippingNote)        ;  //承运人补充电话(可选)
//            kaiyunShippingNote.setLoad_lng              (hyShippingNote)        ;  //装货地经度(可选)
//            kaiyunShippingNote.setLoad_lat              (hyShippingNote)        ;  //装货地纬度(可选)
//            kaiyunShippingNote.setUnload_lng            (hyShippingNote)        ;  //卸货地经度(可选)
//            kaiyunShippingNote.setUnload_lat            (hyShippingNote)        ;  //卸货地纬度(可选)
            kaiyunShippingNote.setBiz_type("01");  //业务类型(传入代码，01-干线普货运输, 02-城市配送, 03-农村配送, 04-集装箱运输, 99-其他)
            kaiyunShippingNote.setDeliver_contact_name(hyShippingNote.getSendContactName());  //发货人姓名
            kaiyunShippingNote.setDeliver_contact_mobile(hyShippingNote.getSendContactTel());  //发货人电话
            kaiyunShippingNote.setDeliver_contact_addr(hyShippingNote.getSendAddress());  //发货人地址
//            kaiyunShippingNote.setDeliver_contact_id    (hyShippingNote)        ;  //发货人证件号
            kaiyunShippingNote.setConsi_contact_addr(hyShippingNote.getSendAddress());  //收货人地址


            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(kaiyunShippingNote), Map.class);
            Long _aop_strtotime = System.currentTimeMillis() / 1000;
            //获取签名
            TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
            log.info("创建和编辑运单：" + map2);
            HttpEntity reqEntity = null;
            try {
                reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                String result = TestHttpClientUtil.httpPost(url+"/tax/waybill/edit?appid=" + appid +
                        "&_aop_strtotime=" + _aop_strtotime, reqEntity);
                ObjectMapper objectMapper = new ObjectMapper();
                ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
                log.info(resultDto);
                if(resultDto!=null){
                    if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                        return Result.OK(result);
                    }else{
                        return Result.error(resultDto.getMsg());
                    }
                }else{
                    return Result.error("数据转换失败"+result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.toString());
            }
        } else {
            return Result.error("数据为空");
        }
    }


    /**
     * 确认发货和到达
     *
     * @param shippingNumber 运单号
     * @param type    装卸货类型 0 装货 1 卸货
     * @return
     */
    public Result<?> taxwaybillconfirm(String shippingNumber, String type) {
        // 实体类转换为Map
        Map<String, String> map2 = new HashMap<>();
        map2.put("order_no", shippingNumber);

        HyShippingNote shippingNote = shippingNoteService.getByShippingNoteNumer(shippingNumber);
        Date statusDtReceive = shippingNote.getStatusDtReceive();
        Date statusDtUnloading = shippingNote.getStatusDtUnloading();
        Long _aop_strtotime = System.currentTimeMillis() / 1000;
        if (type.equals("0")) {
            map2.put("load_time", String.valueOf(statusDtReceive.getTime() /1000));

            map2.put("load_lng", shippingNote.getSendLongitude().toString());
            map2.put("load_lat", shippingNote.getSendLatitude().toString());
        } else if (type.equals("1")) {
            map2.put("unload_time", String.valueOf(statusDtUnloading.getTime()/1000));
            map2.put("unload_lng", shippingNote.getReceiveLongitude().toString());
            map2.put("unload_lat", shippingNote.getReceiveLatitude().toString());
        } else {
            return Result.error("装卸货类型错误");
        }
//        Long _aop_strtotime = System.currentTimeMillis() / 1000;
        //获取签名
        TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
        log.info("确认发货和到达接口参数：" + map2);
        HttpEntity reqEntity = null;
        try {
            reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
            String result = TestHttpClientUtil.httpPost(url+"/tax/waybill/confirm?appid=" + appid +
                    "&_aop_strtotime=" + _aop_strtotime, reqEntity);
            ObjectMapper objectMapper = new ObjectMapper();
            ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
            log.info(resultDto);
            if(resultDto!=null){
                if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                    return Result.OK(result);
                }else{
                    return Result.error(resultDto.getMsg());
                }
            }else{
                return Result.error("数据转换失败"+result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        }
    }


    /**
     * 查询运单审核状态
     *
     * @param orderNo 运单号
     * @param
     * @return
     */
    public Result<?> taxwaybillgetStatus(String orderNo) {
        // 实体类转换为Map
        Map<String, String> map2 = new HashMap<>();
        map2.put("order_no", orderNo);
        Long _aop_strtotime = System.currentTimeMillis() / 1000;
        //获取签名
        TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
        log.info("查询运单审核状态：" + map2);
        HttpEntity reqEntity = null;
        try {
            reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
            String result = TestHttpClientUtil.httpPost(url+"/tax/waybill/getStatus?appid=" + appid +
                    "&_aop_strtotime=" + _aop_strtotime, reqEntity);
            ObjectMapper objectMapper = new ObjectMapper();
            ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
            log.info(resultDto);
            if(resultDto!=null){
                if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                    return Result.OK(result);
                }else{
                    return Result.error(resultDto.getMsg());
                }
            }else{
                return Result.error("数据转换失败"+result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        }
    }

    /**
     * 支付流水 - 删除
     *
     */
    public Result<?> delBill(HyShippingNoteBill hyShippingNoteBill) {
        // 实体类转换为Map
        Map<String, String> map2 = new HashMap<>();
        map2.put("order_no", hyShippingNoteBill.getShippingNoteNumber());
        map2.put("bank_order_no", hyShippingNoteBill.getBillNum());

        Long _aop_strtotime = System.currentTimeMillis() / 1000;
        //获取签名
        TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
        log.info("支付流水 - 删除参数：" + map2);
        HttpEntity reqEntity = null;
        try {
            reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
            String result = TestHttpClientUtil.httpPost(url+"/tax/payinfo/delinfo?appid=" + appid +
                    "&_aop_strtotime=" + _aop_strtotime, reqEntity);
            ObjectMapper objectMapper = new ObjectMapper();
            ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
            log.info("支付流水 - 删除返回："+resultDto);
            if(resultDto!=null){
                if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                    return Result.OK(result);
                }else{
                    return Result.error(resultDto.getMsg());
                }
            }else{
                return Result.error("支付流水 - 删除,数据转换失败"+result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.toString());
        }
    }

    /**
     * 支付流水 - 新增
     *
     * @param req
     * @param hyShippingNoteBills
     * @return
     */
    public Result<?> addBill(HttpServletRequest req, List<HyShippingNoteBill> hyShippingNoteBills, HyShippingNote hyShippingNote) {

        String domainNamePic = yuming + "/static/";
        String domainNamePdf = yuming + "/bank/";

        //遍历该运单所有银行回单，先校验所有流水是否都有回单
        for (HyShippingNoteBill hyShippingNoteBill : hyShippingNoteBills) {
            if (StrUtil.isEmpty(hyShippingNoteBill.getBankHdImg()) && StrUtil.isEmpty(hyShippingNoteBill.getBankHd())) {
                return Result.error(hyShippingNote.getShippingNoteNumber() + " ,请先下载银行回单");
            }

            boolean hdimg = FileUtils.getFile(this.uploadpath + "/" + hyShippingNoteBill.getBankHdImg()).exists();
            boolean hd = FileUtils.getFile(this.bankpath + "/" + hyShippingNoteBill.getBankHd()).exists();
            if (!hdimg && !hd) {
                log.error("银行回单文件不存在, {} {}", hdimg, hd);
                return Result.error(hyShippingNote.getShippingNoteNumber() + " ,银行回单文件不存在");
            }
        }

        String result = StrUtil.EMPTY;
        for (HyShippingNoteBill hyShippingNoteBill : hyShippingNoteBills) {
            //业务数据
            KaiyunBill kaiyunCarrier = new KaiyunBill();

            if (StrUtil.isNotEmpty(hyShippingNoteBill.getBankHdImg())) {
                //优先使用图片
                kaiyunCarrier.setPay_pic(domainNamePic + hyShippingNoteBill.getBankHdImg());//              支付凭证图片URL[必填]
            } else if (StringUtils.isNotEmpty(hyShippingNoteBill.getBankHd())) {
                //没有图片也可以凑合用PDF
                kaiyunCarrier.setPay_pic(domainNamePdf + hyShippingNoteBill.getBankHd());//              支付凭证图片URL[必填]
            }

            kaiyunCarrier.setOrder_no(hyShippingNote.getShippingNoteNumber());//                     合作方唯一业务单号[必填]
            kaiyunCarrier.setPay_style("线上支付");//                    支付方式[必填]
            kaiyunCarrier.setPay_channel_code("103");//            支付渠道[查看附加数据#渠道编码][必填]

//            kaiyunCarrier.setPay_pic_ext();//              扩展图片URL[可选]
            kaiyunCarrier.setBank_order_no(hyShippingNoteBill.getBillNum());//              回单编号[必填]
            kaiyunCarrier.setPay_sno(hyShippingNoteBill.getBillNum());//               支付流水号[必填]
            kaiyunCarrier.setPay_amount(hyShippingNoteBill.getAmt().multiply(new BigDecimal("100")).toString());//               支付金额(单位：分)[必填]
            kaiyunCarrier.setPayee_name(hyShippingNoteBill.getCraccname());//               收款人姓名[必填]
            kaiyunCarrier.setBank_card_no(hyShippingNoteBill.getCraccno() + hyShippingNoteBill.getCrlogaccno());//               银行卡号[必填]
            kaiyunCarrier.setPay_time(String.valueOf(hyShippingNote.getPayDt().getTime() / 1000));//                支付成功时间戳[必填]
//            kaiyunCarrier.setRemark();//                备注[可选]


            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(kaiyunCarrier), Map.class);
            Long _aop_strtotime = System.currentTimeMillis() / 1000;
            //获取签名
            TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
            log.info("开运支付流水接口请求 -> {}", map2);
            HttpEntity reqEntity = null;
            try {
                reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                result = TestHttpClientUtil.httpPost(url + "/tax/payinfo/addinfo?appid=" + appid +
                        "&_aop_strtotime=" + _aop_strtotime, reqEntity);
                ObjectMapper objectMapper = new ObjectMapper();
                ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
                log.info("开运支付流水回执 <- {}", JSONUtil.toJsonStr(resultDto));
                if (resultDto != null) {
                    if (resultDto.getCode().equals("200") || resultDto.getCode().equals("5001") || resultDto.getCode().equals("6001")) {
                        continue;
                    } else {
                        return Result.error(resultDto.getMsg());
                    }
                } else {
                    return Result.error("数据转换失败" + result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.toString());
            }
        }

        return Result.OK(result);
    }


    /**
     * 推送轨迹
     *
     * @param req
     * @param vehicle
     * @return
     */
    public Result<?> addTrack(HttpServletRequest req, HyVehicle vehicle, HyShippingNote hyShippingNote) throws ParseException {

        if (vehicle != null) {
            //业务数据

            String domainName = req.getScheme() + "://" + req.getServerName()+"/";

            Map<String, String> map2 = new HashMap<>();

            /*车辆经纬度点列表(多个点以‘|’ 分隔)
            每个点含下面8个项目，项目之间已‘,’分隔
            1. 车牌号码，字符串
            2. gps时间，unixtime时间戳
            3. 速度，单位：米/小时，整数
            4. 里程，单位：米，整数
            5. lat，纬度*1000000，整数
            6. lng，经度*1000000'，
            7. agl，正北方向夹角，（0--359 ，0正北）
            8. hgt，海拔，单位：米*/
            String startTime = DateUtils.dateTimeToString(hyShippingNote.getStatusDtLoading());
            String endTime = DateUtils.dateTimeToString(hyShippingNote.getStatusDtUnloading());
            WaybillRouteVO routerPath = waybillRouteService.getRouterPath(vehicle.getVehicleNumber(), startTime, endTime, "");
            List<PointDataListVO> pointDataList = routerPath.getPointDataList();
            String guiji = "";
            for (PointDataListVO pointDataListVO : pointDataList) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = format.parse(pointDataListVO.getReceiveTime());
                //            车牌号码,时间戳,速度,里程,纬度,经度,方向,海拔|车牌号码,时间戳,速度,里程,纬度,经度,方向,海拔
                String dguiji = vehicle.getVehicleNumber() + "," + date.getTime() / 1000 + ",0" + ",0," + doubleTransitionString(pointDataListVO.getLat()) + "," +  doubleTransitionString(pointDataListVO.getLng()) + ",0" + ",0";
                guiji = guiji + dguiji + "|";
            }
            map2.put("points", guiji);

            // 实体类转换为Map
            Long _aop_strtotime = System.currentTimeMillis() / 1000;
            //获取签名
            TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
            log.info("推送轨迹接口,轨迹数量: {}" + pointDataList.size());
            HttpEntity reqEntity = null;
            try {
                reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                String result = TestHttpClientUtil.httpPost(url+"/tax/Track/add?appid=" + appid +
                        "&_aop_strtotime=" + _aop_strtotime, reqEntity);
                ObjectMapper objectMapper = new ObjectMapper();
                ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
                log.info(resultDto);
                if(resultDto!=null){
                    if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                        return Result.OK(result);
                    }else{
                        return Result.error(resultDto.getMsg());
                    }
                }else{
                    return Result.error("数据转换失败"+result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.toString());
            }
        } else {
            return Result.error("推送轨迹数据为空");
        }
    }

    public static void main(String[] args) {

        System.out.println(doubleTransitionString("39.58941")); // 输出结果
    }

    public static String doubleTransitionString(String num){
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);      //关闭科学计数法
        nf.setMaximumFractionDigits(0);   //定义保留几位小数
        String format = nf.format(Double.valueOf(num)*1000000);
        return format;
    }


    /**
     * 发布货源
     *
     * @param req
     * @param order
     * @return
     */
    public Result<?> addOrder(HttpServletRequest req, HyOrder order) {

        if (order != null) {
            //业务数据

            String domainName = yuming+"/static/";

            KaiyunOrder kaiyunOrder = new KaiyunOrder();
            kaiyunOrder.setGoods_no(order.getId());//   合作方货源编号(唯一)
            kaiyunOrder.setGoods_price(order.getShippingUnitPrice().multiply(new BigDecimal("100")).toString());//   运输单价(单位：分)
            kaiyunOrder.setPrice_type(order.getShippingType()=="4"?"2":order.getShippingType());//   价格类型(单价:1、整车价:2)
            kaiyunOrder.setGoods_type("0100");//   货物类型(参考下方"附加数据")
            kaiyunOrder.setGoods_name(order.getDescriptionOfGoods());//   货物名称
            kaiyunOrder.setGoods_num("1000");//   货量
            kaiyunOrder.setGoods_unit("0");//   货量单位(见下方附加数据)
            kaiyunOrder.setLoad_time(String.valueOf(System.currentTimeMillis() / 1000));//   起运时间(时间戳)
            kaiyunOrder.setLoad_place_id(order.getSendAreaCode());//   装货地id(省市区编码或港口编码)
            kaiyunOrder.setUnload_place_id(order.getReceiveAreaCode());//   卸货地id(省市区编码或港口编码)
            kaiyunOrder.setLoad_place_detail(order.getSendAddress());//   装货地详细地址(不包含省市区)
            kaiyunOrder.setUnload_place_detail(order.getReceiveAddress());//   卸货地详细地址(不包含省市区)
            kaiyunOrder.setShipper_contact_name(order.getSendContactName());//   托运方联系人名称
            kaiyunOrder.setShipper_contact_mobile(order.getReceiveContactTel());//   托运方手机号
            kaiyunOrder.setConsi_name(order.getReceiveAddressName());//   收货方名称
            kaiyunOrder.setConsi_contact_name(order.getReceiveContactName());//   收货联系人姓名
            kaiyunOrder.setConsi_contact_mobile(order.getReceiveContactTel());//   收货人手机号
/*            kaiyunOrder.setLoad_lng();//   装货地经度(可选)
            kaiyunOrder.setLoad_lat();//   装货地纬度(可选)
            kaiyunOrder.setUnload_lng();//   卸货地经度(可选)
            kaiyunOrder.setUnload_lat();//   卸货地纬度(可选)*/


            // 实体类转换为Map
            Map<String, String> map2 = JSON.parseObject(JSON.toJSONString(kaiyunOrder), Map.class);
            Long _aop_strtotime = System.currentTimeMillis() / 1000;
            //获取签名
            TestHttpClientUtil.makeSignature(appid, appsecret, _aop_strtotime, map2);
            log.info("发布货源接口参数：" + map2);
            HttpEntity reqEntity = null;
            try {
                reqEntity = new StringEntity(JSONUtil.toJsonStr(map2), "utf-8");
                String result = TestHttpClientUtil.httpPost(url+"/car/PlanGoods/add?appid=" + appid +
                        "&_aop_strtotime=" + _aop_strtotime, reqEntity);
                ObjectMapper objectMapper = new ObjectMapper();
                ResultDto resultDto = objectMapper.readValue(result, ResultDto.class); // 将JSON字符串转换为Person对象
                log.info(resultDto);
                if(resultDto!=null){
                    if(resultDto.getCode().equals("200") || resultDto.getCode().equals("5001")|| resultDto.getCode().equals("6001")){
                        return Result.OK(result);
                    }else{
                        return Result.error(resultDto.getMsg());
                    }
                }else{
                    return Result.error("数据转换失败"+result);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.toString());
            }
        } else {
            return Result.error("发布货源数据为空");
        }
    }

}




